package com.example.controller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author xiaoming
 * @version 1.0
 * @date 2019-05-01 20:47
 **/
@Controller
@RequestMapping(value = "/file")
public class FileController {
    private static String UPLOADED_FOLDER = "d://DFS//";
    private Log log = LogFactory.getLog(FileController.class);

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String uploadFile(@RequestParam(value = "file") MultipartFile file,
                             RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "Place select a file to upload");
            return "redirect:/uploadStatus";
        }

        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());

            Files.write(path, bytes);

            redirectAttributes.addFlashAttribute("message", "Success: " + file.getOriginalFilename());

        } catch (IOException e) {
            e.printStackTrace();
        }

        log.info("文件上传");

        return "redirect:/uploadStatus";
    }

}
